package com.xuanwu.ai.flow.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xuanwu.ai.core.utils.IdWorker;
import com.xuanwu.ai.flow.dto.CommonContextDTO;
import com.xuanwu.ai.flow.dto.FlowDataReqDTO;
import com.xuanwu.ai.flow.dto.FlowDataResDTO;
import com.xuanwu.ai.flow.mapper.FlowDataMapper;
import com.xuanwu.ai.flow.model.FlowData;
import com.xuanwu.ai.jdbc.page.Pagination;
import com.yomahub.liteflow.flow.LiteflowResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.xuanwu.ai.flow.constant.GlobalConstant.*;

@Service
@Slf4j
public class FlowDataServiceImpl {
    @Autowired
    private FlowDataMapper flowDataMapper;
    @Autowired
    private IdWorker idWorker;

    public void saveFlowData(LiteflowResponse response) {
        if (response == null)
            return;

        FlowData flowData = new FlowData();
        flowData.setId(idWorker.genId());
        flowData.setTenantId(Integer.valueOf(response.getContextBean(CommonContextDTO.class).getTenantId()));
        flowData.setFlowId(response.getContextBean(CommonContextDTO.class).getFlowId());
        flowData.setFlowVersionId(response.getContextBean(CommonContextDTO.class).getFlowVersionId());
        flowData.setFlowRequestId(response.getRequestId());
        if(response.getContextBean(CommonContextDTO.class).getNodeJsonResult() != null)
            flowData.setFlowData(response.getContextBean(CommonContextDTO.class).getNodeJsonResult().toJSONString());
        flowData.setStatus(response.isSuccess() ? FLOW_EXECUTE_SUCCESS : FLOW_EXECUTE_FAIL);

        Date current = new Date();
        flowData.setCreateTime(current);
        flowData.setUpdateTime(current);
        flowDataMapper.insert(flowData);
    }

    public PageInfo<FlowDataResDTO> getFlowDataList(FlowDataReqDTO flowDataReqDTO, Pagination pagination) {
        PageHelper.startPage(pagination);

        return PageInfo.of(flowDataMapper.getFlowDataList(flowDataReqDTO));
    }

    public FlowDataResDTO getFlowDataByRequestId(String requestId) {

        return flowDataMapper.getFlowDataByRequestId(requestId);
    }

}
